const request = require('request'),
     fs = require('fs'),
     wechatApi = require('../config/config').wechatApi;


function getCommonAccessToken() {
    let getCommonAccessTokenUrl = wechatApi.commonAccessTokenApi,
        options = {
            method: 'GET',
            url: getCommonAccessTokenUrl
        };
    return new Promise((resolve, reject) => {
        request(options, function (err, res, body) {
            if (res) {
                resolve(JSON.parse(body));
            } else {
                reject(err);
            }
        });
    })
};

function saveCommonAccessToken() {
    getCommonAccessToken().then(res => {
        let commonAccessToken = res['access_token'];
        fs.writeFileSync('./config/commonAccessToken', commonAccessToken);
    }).catch(err=>{
        console.log('get access_token err',err)
    })
};

function refreshCommonAccessToken() {
    saveCommonAccessToken();
    setInterval(function () {
        saveCommonAccessToken();
    }, 7000*1000);
};

module.exports = refreshCommonAccessToken;